package com.video.ui.video;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.video.R;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class VideoFragment extends Fragment {
    private RVAdp adp;
    List<VideoBean> mList = new ArrayList<>();
    private SharedPreferences sp;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root=inflater.inflate(R.layout.fragment_video, container, false);
        RecyclerView rv = root.findViewById(R.id.rv);
        sp = requireContext().getSharedPreferences("data", Context.MODE_PRIVATE);

        mList.add(new VideoBean("http://10.147.17.1:8000/1004650402.mp4","这是一条视频"));
        mList.add(new VideoBean("https://img-baofun.zhhainiao.com/market/b99b51e6c7945c9d5565861d397451cb_preview.mp4","这是一条视频"));
        mList.add(new VideoBean("https://img-baofun.zhhainiao.com/pcwallpaper_ugc/preview/83cc918f8ef325ea6ceaaaf55dccaf5d_preview.mp4","这是一条视频"));
        mList.add(new VideoBean("https://img-baofun.zhhainiao.com/pcwallpaper_ugc/preview/ce9dd03aeeabe59654bbe067b35b8dd2_preview.mp4","这是一条视频"));
//

        new PagerSnapHelper().attachToRecyclerView(rv);
        rv.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));


        adp=new RVAdp(requireContext(),mList);
        rv.setAdapter(adp);


        String url="http://"+sp.getString("ip","127.0.0.1")+":"+sp.getString("port","8000")+sp.getString("dir","/");
        new Thread(() -> { try{
            Element content= Jsoup.connect(url).timeout(5000).get().body();
            Elements contents=content.getElementsByAttribute("href");
            for (Element e:contents) {
                mList.add(new VideoBean(url+e.attr("href"),"这是一条视频"));
                Log.i("emmmmm", "onCreateView: "+url+e.attr("href"));
            }
            adp.notifyDataSetChanged();

//            Log.i("emmmmm", "onCreateView: "+mList.toString());

        }catch (Exception ignored){} }).start();


        return root;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (adp.mp.isPlaying()){
            adp.mp.stop();
            adp.mp.release();
        }
    }
}